#include "testinclude.hpp"

static const string inputfilePos = "input.txt";
static const string outputfilePos = "output.txt";

/*
 * read data from file, 
 * input const std::string& fileName
 * return pair<bool, vector<string>>, if OK, first true, second filecontent; else first false, second ""
 */
pair<bool, vector<string>> read_file_to_string(std::string const& fileName)
{
	std::ifstream fin(fileName, std::ios::in);

    if (!fin.is_open()) {
		cout << "fileName:" << fileName << " not found" << endl;
        return {false, {}};
    } else {
		vector<string> res;
		char line[65536] = {0};
		while(fin.getline(line, sizeof(line)))
		{
			res.emplace_back((string)line);
		}
		fin.clear();
		fin.close();
		return {true, res};
    }
}

/*
 * write data to file
 * input string const& fileName, string const& content
 * return bool, if OK, true; else first
 */
bool write_string_to_file(string const& fileName, string const& content)
{
	cout << "content:" << content << endl;
    std::fstream s(fileName, s.out);
    if (!s.is_open()) {
        return false;
    } else {
		s << content;
		s.close();
		return true;
    }
}

/*
 * for sort test
 * note: must input with exactedly three para, second must be a number type, range:[0, 9999],
 *    third must be a directory, eq: ../xxx/yyy
 * return code
 *        0: OK; 
 *        10: para error;
 *        10: input file not occured; 
 *        10: input data not valid; 
 *        10: output file cannot saved;
 *        1: ADDRESS_SANITIZER_ERROR
 *        99: for debug of cppJudgeSystem
 *        cannot use 3-10, they are predifined
 *        the other codes are not predifined, if have other exit (program terminated by inside fuction runtime error!, if occur, tell me)
 */
int main(int argc, char* argv[]) {	
	if (argc != 3){
		//cout << "argc not valid" << endl;
		
		return 99;
	}else{
		//cout << "argc valid" << endl;
		
		string para(argv[1]);
		int val = 0;
		int count = 0;
		for(auto& iters:para){
			if (!isdigit(iters) || count >= 4){
				return 99;
			}else{
				val = val*10 + iters - '0';
				count++;
			}
		}
		
		//cout << "argv[1] OK" << endl;
		
		string directory = argv[2];
		
		//cout << "argv[2] OK" << endl;
		
		Solution s = Solution();
		
		//read data from input.txt
		pair<bool, vector<string>> readret = read_file_to_string(directory + to_string(val) + inputfilePos);
		if (!readret.first){
			return 99;
		}
		
		//cout << "run program OK" << endl;
		
		//may use JSONlib to decode fileret.second!
		string res = s.sortString(readret.second[0]);
		
		//may use JSONlib to encode res!
		//save output to XXXXoutput.txt
		bool saveret = write_string_to_file(directory + to_string(val) + outputfilePos, res);
		//cout << "saveret OK" << endl;
		if (!saveret){
			return 99;
		}else{
			return 0;
		}
	}
}
